package com.taiyi.renaissancemall.ui.main.order

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View.*
import android.view.WindowManager
import com.alipay.sdk.app.PayTask
import com.taiyi.renaissancemall.R
import com.taiyi.renaissancemall.Utils.PayResult
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.load
import com.taiyi.renaissancemall.base.BaseActivity
import com.taiyi.renaissancemall.base.MyApp
import com.taiyi.renaissancemall.bean.*
import com.taiyi.renaissancemall.ui.main.paysuccess.PaySuccessActivity
import com.taiyi.renaissancemall.ui.mine.address.ShippingAddressActivity
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.android.synthetic.main.activity_fill_order.aliPayTv
import kotlinx.android.synthetic.main.activity_fill_order.availableBalanceTv
import kotlinx.android.synthetic.main.activity_fill_order.balancePaymentTv
import kotlinx.android.synthetic.main.activity_fill_order.defaultTv
import kotlinx.android.synthetic.main.activity_fill_order.nameTv
import kotlinx.android.synthetic.main.activity_fill_order.orderRemarksContentEt
import kotlinx.android.synthetic.main.activity_fill_order.phoneNumberTv
import kotlinx.android.synthetic.main.activity_fill_order.realPaymentTv
import kotlinx.android.synthetic.main.activity_fill_order.selectShippingAddressTv
import kotlinx.android.synthetic.main.activity_fill_order.shippingAddressTv
import kotlinx.android.synthetic.main.activity_fill_order.submitOrdersTv
import kotlinx.android.synthetic.main.activity_fill_order.top
import kotlinx.android.synthetic.main.activity_fill_order.weChatTv
import kotlinx.android.synthetic.main.base_top_white_background_layout.*
import kotlinx.android.synthetic.main.new_activity_fill_order.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.text.DecimalFormat

class ProductFillOrderActivity : BaseActivity<FillOrderView, FillOrderPresent>(), FillOrderView {

    var commodityspecid = ""
    var payMethod = "2"
    var aliPayOrderId = ""

    override fun getLayoutId(): Int = R.layout.new_activity_fill_order

    override fun initPresenter(): FillOrderPresent = FillOrderPresent()

    var selAddressId: String = ""

    override fun initViews(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        EventBus.getDefault().register(this)
        commodityspecid = intent.getStringExtra("commodityspecid")
        titleTv.text = getString(R.string.fillOrder)
        aliPayTv.isSelected = true
        showProgress()
        presenter.getProductOrderInfo()
    }

    @Subscribe
    fun refreshData(address: AddressListBean.AddresslistBean) {
        if (selAddressId == "") {
            selectShippingAddressTv.visibility = INVISIBLE
            group.visibility = VISIBLE
        }
        selAddressId = address.useraddress_id
        if (address.type == "0") {
            defaultTv.visibility = GONE
            defaultOneTv.visibility = VISIBLE
        } else {
            defaultTv.visibility = VISIBLE
            defaultOneTv.visibility = GONE
        }
        nameTv.text = address.name
        phoneNumberTv.text = getString(R.string.contactNumber) + " " + address.tel
        shippingAddressTv.text =
            address.provincename + address.cityname + address.areaname + address.address
        presenter.getFreight()
    }

    override fun initData() {

    }

    override fun initEvent() {

        phoneNumberTv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }
        selectShippingAddressTv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }
        aliPayTv.setOnClickListener {
            payMethod = "2"
            aliPayTv.isSelected = true
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = false
        }
        weChatTv.setOnClickListener {
            payMethod = "1"
            aliPayTv.isSelected = false
            weChatTv.isSelected = true
            balancePaymentTv.isSelected = false
        }
        balancePaymentTv.setOnClickListener {
            payMethod = "3"
            aliPayTv.isSelected = false
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = true
        }
        submitOrdersTv.setOnClickListener {
            if (selAddressId == "") {
                ToastUtils.showLongToast("请选择收货地址")
                return@setOnClickListener
            }
            showProgress()
            presenter.productCommitOrder()
        }
        backIv.setOnClickListener {
            finish()
        }
        editAddressIv.setOnClickListener {
            startActivity(Intent(this, ShippingAddressActivity::class.java))
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(top).init()
    }

    val SDK_PAY_FLAG = 1001

    override fun getRemark(): String = orderRemarksContentEt.text.toString()
    override fun getOrderStateSuccess() {
        hideProgress()
        var intent = Intent(this, PaySuccessActivity::class.java)
        intent.putExtra("payWay", payMethod)
        intent.putExtra("payAmount", totalPrice)
        intent.putExtra("orderId", aliPayOrderId);
        startActivity(intent)
        finish()
    }

    override fun getOrderStateFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getNum(): String = intent.getStringExtra("num")
    override fun getFreightSuccess(freightBean: FreightBean?) {
        if (freightBean?.sumyunfei != null) {
            freightTv.text = "￥" + freightBean?.sumyunfei
            realPaymentTv.text = "￥" + (realPrice + freightBean?.sumyunfei?.toDouble()!!)
            totalPrice = (realPrice + freightBean?.sumyunfei?.toDouble()!!).toString()
        } else {
            totalPrice = realPrice.toString()
            realPaymentTv.text = "￥" + realPrice
        }

    }

    override fun getFreightFailure(msg: String?) {
        toast(msg)
    }

    override fun commitOrderFailure(msg: String?) {
        hideProgress()
        ToastUtils.showLongToast(msg)
    }

    override fun getOrderId(): String = aliPayOrderId

    override fun getShopCarId(): String = commodityspecid
    override fun commitOrderSuccess(commitOrderBean: CommitOrderBean?) {
        hideProgress()
        aliPayOrderId = commitOrderBean?.orderid!!
        if ("2" == payMethod) {//支付宝支付

            val stInfo = commitOrderBean?.aliparam
            Log.i("ddddddddddd", "------$stInfo")
            var payRunnable = Runnable {
                var alipay = PayTask(this)

                var result = alipay.payV2(stInfo, true)
                var msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            var payThread = Thread(payRunnable)
            payThread.start()
        } else if ("3" == payMethod) {//余额支付
            showProgress()
            presenter.findOrderState();
        } else if ("1" == payMethod) {//微信支付
            //这里的appid，替换成自己的即可
            var api = MyApp.getWxApi()
            api.registerApp(MyApp.getAppId())
            //这里的bean，是服务器返回的json生成的bean
            var payRequest = PayReq()
            payRequest.appId = commitOrderBean.appid
            payRequest.partnerId = commitOrderBean.partnerid
            payRequest.prepayId = commitOrderBean.prepayid
            payRequest.packageValue = "Sign=WXPay";//固定值
            payRequest.nonceStr = commitOrderBean.noncestr
            payRequest.timeStamp = commitOrderBean.timestamp
            payRequest.sign = commitOrderBean.sign

            //发起请求，调起微信前去支付
            api.sendReq(payRequest);
        }
    }

    var totalPrice = ""


    @Subscribe
    fun paySuccess(s: String) {
        if (s.startsWith("paySuccess")) {
            showProgress()
            presenter.findOrderState()
        }
    }

    private val mHandler: Handler = object : Handler() {

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    var payResult = PayResult(msg.obj as MutableMap<String, String>?)
                    var resultInfo = payResult.result
                    if (payResult?.resultStatus == "9000") {
//                        ToastUtils.showLongToast("支付成功---$resultInfo")
                        showProgress()
                        presenter.findOrderState()
                    }

                }
                else ->
                    ToastUtils.showLongToast("支付异常")
            }

        }
    }
    var realPrice = 0.0
    var decimalFormat = DecimalFormat("#0.00");
    override fun getAddressId(): String = selAddressId

    override fun getPayType(): String = payMethod
    override fun getProductOrderInfoSuccess(toFillOrderBean: ProductFillOrderBean?) {
        hideProgress()
        var liquannumti = toFillOrderBean?.user?.liquannumti
        availableBalanceTv.text = "(可用余额" + decimalFormat.format(liquannumti) + ")"
        var ifhui = toFillOrderBean?.ifhui


        var product = toFillOrderBean?.product
        iv.load(product?.smallimgurl!!)
        quantityTv.text = "x" + product?.num
        productTitleTv.text = product?.name

        specificationTv.text = product?.typename
        if (toFillOrderBean?.ifhui == "1") {//会员，
            memberPrice.visibility = VISIBLE
            bvPriceTv.text = product?.hybvprice.toString() + "BV"
            memberPriceTv.text = "￥" + product?.hyprice.toString()
            realPaymentTv.text = "￥" + decimalFormat.format(product?.hyprice * product?.num.toInt())
            realPrice = product?.hyprice * product?.num.toInt()
        } else {
            memberPrice.visibility = GONE
            bvPriceTv.text = product?.bvprice.toString() + "BV"
            memberPriceTv.text = "￥" + product?.price.toString()
            realPaymentTv.text = "￥" + decimalFormat.format(product?.price * product?.num.toInt())
            realPrice = product?.price * product?.num.toInt()
        }
        var addressParams = toFillOrderBean?.addressParams
        if (addressParams == null) {
            selectShippingAddressTv.visibility = VISIBLE
            group.visibility = INVISIBLE
        } else {
            group.visibility = VISIBLE
            selectShippingAddressTv.visibility = INVISIBLE
            selAddressId = addressParams.useraddress_id.toString()
            nameTv.text = addressParams.name
            phoneNumberTv.text = getString(R.string.contactNumber) + " " + addressParams.tel
            shippingAddressTv.text =
                addressParams.provincename + addressParams.cityName + addressParams.areaName + addressParams.address
            presenter.getFreight()
        }

    }

    override fun getOrderInfoSuccess(toFillOrderBean: ToFillOrderBean?) {
    }

    override fun getProductOrderInfoFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getCommSpecId(): String = commodityspecid

    override fun getOrderInfoFailure(msg: String?) {
        ToastUtils.showLongToast(msg)
    }
}


